package com.itentbase.match.schedule;

import com.itentbase.match.common.utils.DateSplicingUtil;
import com.itentbase.match.pojo.po.FootballMatch;
import com.itentbase.match.service.FootballMatchService;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 获取赛事信息调度器
 * @author:wjl
 * @create: 2024-12-30 09:25
 */
@Slf4j
@Component
public class GetMatchInfoSchedule {
    @Resource
    private FootballMatchService footballMatchService;
    @Scheduled(cron = "0 5 0 * * ?")
    @Scheduled(cron = "0 5 12 * * ?")
    public void getAllMatchInfo() {

        // 获取请求（需联网）
        String url = "https://webapi.sporttery.cn/gateway/jc/football/getMatchListV1.qry?clientCode=3001";
        List<FootballMatch> footballMatchList = new ArrayList<>();

        try {
            // 获取 JSON 响应字符串
            String jsonResponse = Jsoup.connect(url).ignoreContentType(true).execute().body();

            JSONObject jsonObject = new JSONObject(jsonResponse);
            JSONObject value = jsonObject.getJSONObject("value");
            JSONArray matchInfoList = value.getJSONArray("matchInfoList");

            for (int i = 0; i < matchInfoList.length(); i++) {
                JSONObject match = matchInfoList.getJSONObject(i);
                JSONArray subMatchList = match.getJSONArray("subMatchList");

                for (int j = 0; j < subMatchList.length(); j++) {
                    JSONObject subMatch = subMatchList.getJSONObject(j);
                    int matchIds = subMatch.getInt("matchId");

                    // 拼接详细信息URL
                    String inforurl = "https://webapi.sporttery.cn/gateway/uniform/football/getMatchHeadV1.qry?source=web&sportteryMatchId=" + matchIds;
                    String jsonResponseinfo = Jsoup.connect(inforurl).ignoreContentType(true).execute().body();
                    JSONObject jsonObjectinfo = new JSONObject(jsonResponseinfo);

                    String season = jsonObjectinfo.getJSONObject("value").optString("seasonName", "");
                    String roundNum = jsonObjectinfo.getJSONObject("value").optString("gameweek", "");
                    String awayTeamPreMatchRank = jsonObjectinfo.getJSONObject("value").optJSONObject("wbsjStats").optJSONObject("away").optString("ranking", "");
                    String homeTeamPreMatchRank = jsonObjectinfo.getJSONObject("value").optJSONObject("wbsjStats").optJSONObject("home").optString("ranking", "");

                    // 拼接赔率URL获取让球数
                    String scoreurl = "https://webapi.sporttery.cn/gateway/jc/football/getFixedBonusV1.qry?clientCode=3001&matchId=" + matchIds;
                    String jsonResponsescore = Jsoup.connect(scoreurl).ignoreContentType(true).execute().body();
                    JSONObject jsonObjectscore = new JSONObject(jsonResponsescore);
                    JSONArray hhadList = jsonObjectscore.getJSONObject("value").optJSONObject("oddsHistory").optJSONArray("hhadList");
                    String giveBall = hhadList != null && hhadList.length() > 0 ? hhadList.getJSONObject(0).optString("goalLine", "") : "";
                    JSONArray hadList = jsonObjectscore.getJSONObject("value").optJSONObject("oddsHistory").optJSONArray("hadList");
                    boolean closeWdl = hadList != null? true : false;

                    String matchNumStr = subMatch.optString("matchNumStr", "");
                    String leagueAbbName = subMatch.optString("leagueAbbName", "");
                    String leagueAllName = subMatch.optString("leagueAllName", "");
                    String homeTeamAllName = subMatch.optString("homeTeamAllName", "");
                    String awayTeamAllName = subMatch.optString("awayTeamAllName", "");
                    String matchDate = subMatch.optString("matchDate", "");
                    String matchTime = subMatch.optString("matchTime", "");
                    LocalDateTime matchDateTime = DateSplicingUtil.getDateSplicing(matchDate, matchTime);

                    FootballMatch footballMatch = new FootballMatch();
                    footballMatch.setId(matchIds);
                    footballMatch.setMatchNumStr(matchNumStr);
                    footballMatch.setStartDate(matchDateTime.toLocalDate());
                    footballMatch.setMatchDateTime(matchDateTime);
                    footballMatch.setLeagueAbbName(leagueAbbName);
                    footballMatch.setLeagueAllName(leagueAllName);
                    footballMatch.setSeason(season);
                    footballMatch.setRoundNum(roundNum);
                    footballMatch.setHomeTeamAbbName(homeTeamAllName);
                    footballMatch.setHomeTeamAllName(homeTeamAllName);
                    footballMatch.setAwayTeamAbbName(awayTeamAllName);
                    footballMatch.setAwayTeamAllName(awayTeamAllName);
                    footballMatch.setHomeTeamPreMatchRank(homeTeamPreMatchRank.isEmpty() ? null : Integer.parseInt(homeTeamPreMatchRank));
                    footballMatch.setAwayTeamPreMatchRank(awayTeamPreMatchRank.isEmpty() ? null : Integer.parseInt(awayTeamPreMatchRank));
                    footballMatch.setGiveBall(giveBall.isEmpty() ? null : Integer.parseInt(giveBall));
                    footballMatch.setSinglePass(false);
                    footballMatch.setSinglePass2(false);
                    footballMatch.setCloseWdl(closeWdl);
                    //TODO 得分数据
//                    footballMatch.setHalfScore("");
//                    footballMatch.setFullScore("");
                    //TODO 比赛状态
//                    footballMatch.setStatus((byte) 0);
                    //创建和更新时间
                    footballMatchList.add(footballMatch);
                }
            }
            log.info("获取赛事信息成功！数据量: {}", footballMatchList.size());
            boolean result = footballMatchService.saveOrUpdateBatch(footballMatchList);
            log.info("批量保存结果: {}", result);

        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
    }

}
